import { 
  WeatherQueryParams, 
  AMapWeatherResponse, 
  WeatherResponse, 
  WeatherErrorResponse,
  LiveWeather,
  ForecastWeather
} from '../types/weather';

export class WeatherService {
  private readonly apiKey: string;
  private readonly baseUrl: string = 'https://restapi.amap.com/v3/weather/weatherInfo';

  constructor() {
    this.apiKey = process.env.AMAP_KEY || '5353e3e981f189bd617e25f875664b35';
  }

  /**
   * 获取天气信息
   * @param params 查询参数
   * @returns 天气信息
   */
  async getWeather(params: WeatherQueryParams): Promise<WeatherResponse | WeatherErrorResponse> {
    try {
      const { city, extensions = 'base' } = params;

      // 构建请求URL
      const url = new URL(this.baseUrl);
      url.searchParams.append('key', this.apiKey);
      url.searchParams.append('city', city);
      url.searchParams.append('extensions', extensions);

      // 发送请求
      console.log('请求URL:', url.toString());
      const response = await fetch(url.toString());
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data: AMapWeatherResponse = await response.json();
      console.log('高德地图API响应:', JSON.stringify(data, null, 2));

      // 检查API响应状态
      if (data.status !== '1') {
        return {
          success: false,
          message: `高德地图API错误: ${data.info}`,
          error: data.infocode
        };
      }

      // 处理响应数据
      if (extensions === 'base' && data.lives && data.lives.length > 0) {
        return {
          success: true,
          message: '获取实时天气成功',
          data: {
            type: 'live',
            weather: data.lives[0]
          }
        };
      } else if (extensions === 'all' && data.forecasts && data.forecasts.length > 0) {
        return {
          success: true,
          message: '获取天气预报成功',
          data: {
            type: 'forecast',
            weather: data.forecasts[0]
          }
        };
      } else {
        return {
          success: false,
          message: '未找到天气数据'
        };
      }

    } catch (error) {
      console.error('获取天气信息失败:', error);
      return {
        success: false,
        message: '获取天气信息失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 获取实时天气
   * @param city 城市名称或编码
   * @returns 实时天气信息
   */
  async getLiveWeather(city: string): Promise<WeatherResponse | WeatherErrorResponse> {
    return this.getWeather({ city, extensions: 'base' });
  }

  /**
   * 获取天气预报
   * @param city 城市名称或编码
   * @returns 天气预报信息
   */
  async getForecastWeather(city: string): Promise<WeatherResponse | WeatherErrorResponse> {
    return this.getWeather({ city, extensions: 'all' });
  }

  /**
   * 验证城市参数
   * @param city 城市名称或编码
   * @returns 是否有效
   */
  validateCity(city: string): boolean {
    if (!city || typeof city !== 'string') {
      return false;
    }
    
    // 去除空格
    city = city.trim();
    
    // 检查是否为空
    if (city.length === 0) {
      return false;
    }

    // 检查长度（城市名称一般不会超过50个字符，城市编码为6位数字）
    if (city.length > 50) {
      return false;
    }

    return true;
  }

  /**
   * 格式化天气数据用于显示
   * @param weatherData 天气数据
   * @returns 格式化后的数据
   */
  formatWeatherData(weatherData: LiveWeather | ForecastWeather): any {
    if ('temperature' in weatherData) {
      // 实时天气数据
      const live = weatherData as LiveWeather;
      return {
        location: `${live.province} ${live.city}`,
        current: {
          weather: live.weather,
          temperature: `${live.temperature}°C`,
          humidity: `${live.humidity}%`,
          wind: `${live.winddirection}风 ${live.windpower}级`,
          updateTime: live.reporttime
        }
      };
    } else {
      // 预报天气数据
      const forecast = weatherData as ForecastWeather;
      return {
        location: `${forecast.province} ${forecast.city}`,
        forecast: {
          updateTime: forecast.reporttime,
          days: forecast.casts.map(cast => ({
            date: cast.date,
            week: cast.week,
            day: {
              weather: cast.dayweather,
              temperature: `${cast.daytemp}°C`,
              wind: `${cast.daywind} ${cast.daypower}级`
            },
            night: {
              weather: cast.nightweather,
              temperature: `${cast.nighttemp}°C`,
              wind: `${cast.nightwind} ${cast.nightpower}级`
            }
          }))
        }
      };
    }
  }
}